<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import _ from 'lodash'
let loading = ref(false)
const localHostText = ref([])
const remoteHostText = ref([])
onMounted(() => {
    getLocalHost()
})

const ipRegExp = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/
const getLocalHost = (showLoading) => {
    if (showLoading) {
        loading.value = true
    }
    electron.ipcRenderer.invoke('getLocalHost').then(result => {
        let localHostArr = []
        let hostArr = result.split('\r\n')
        hostArr.map(item => {
            let ip = _.trim(item).split(/\s+/)[0]
            let hostname = _.trim(item).split(/\s+/)[1]
            if (!ipRegExp.test(ip)) {
                ip = item
                hostname = ''
            }
            if (ip) {
                localHostArr.push({
                    ip,
                    hostname
                })
            }
        })
        localHostText.value = localHostArr

        if (showLoading) {
            loading.value = false
        }
    })
}

const getRemoteHost = () => {
    return electron.ipcRenderer.invoke('getRemoteHost')
}

const updateHost = async () => {
    loading.value = true
    let result = await getRemoteHost()
    let remoteHostArr = []
    let hostArr = result.split('\n')
    hostArr.map(item => {
        if (item) {
            let ip = _.trim(item).split(/\s+/)[0]
            let hostname = _.trim(item).split(/\s+/)[1]
            if (!ipRegExp.test(ip)) {
                ip = item
                hostname = ''
            }
            remoteHostArr.push({
                ip,
                hostname
            })
        }
    })
    remoteHostText.value = remoteHostArr
    remoteHostText.value.map(item => {
        if (item.hostname) {
            let obj = _.find(localHostText.value, { hostname: item.hostname })
            if (obj) {
                if (obj.ip !== item.ip) {
                    obj.ip = item.ip
                    obj.status = 'update'
                    let index = _.findIndex(localHostText.value, { hostname: item.hostname })
                    localHostText.value.splice(index, 1, obj)
                }
            } else {
                localHostText.value.push({ ...item, status: 'add' })
            }
        } else if (_.startsWith(item.ip, '#')) {
            let startStr = ''
            if (_.startsWith(item.ip, '# Update time')) {
                startStr = '# Update time'
            }
            if (_.startsWith(item.ip, '# Update url')) {
                startStr = '# Update url'
            }
            if (_.startsWith(item.ip, '# Star me')) {
                startStr = '# Star me'
            }
            if (startStr) {
                let obj = _.find(localHostText.value, (o) => { return _.startsWith(o.ip, startStr) })
                if (obj) {
                    let index = _.findIndex(localHostText.value, (o) => { return _.startsWith(o.ip, startStr) })
                    if (obj.ip !== item.ip) {
                        obj.ip = item.ip
                        obj.status = 'update'
                        localHostText.value.splice(index, 1, obj)
                    }
                } else {
                    localHostText.value.push({ ...item, status: 'add' })
                }
            } else {
                if (!_.find(localHostText.value, { ip: item.ip })) {
                    localHostText.value.push({ ...item, status: 'add' })
                }
            }
        }
    })
    loading.value = false
}

const saveHost = () => {
    loading.value = true
    let fileStr = ''
    localHostText.value.map(item => {
        let ip = item.ip
        if (ipRegExp.test(item.ip)) {
            ip = _.padEnd(item.ip, 20, ' ')
        }
        fileStr += `${ip}${item.hostname}\r\n`
    })
    electron.ipcRenderer.invoke('updateFile', "C:\\Windows\\System32\\drivers\\etc\\hosts", fileStr).then((res) => {
        loading.value = false
        if (res) {
            ElMessage(res)
        } else {
            electron.ipcRenderer.invoke('updateDns').then(res => {
                ElMessage(res)
            })
        }
    })
}

const openHostFolder = () => {
    electron.ipcRenderer.invoke('openFolder', "C:\\Windows\\System32\\drivers\\etc\\hosts")
}

const updateDns = () => {
    electron.ipcRenderer.invoke('updateDns').then(res => {
        ElMessage(res)
    })
}

</script>
<template>
    <el-row class="btn-wrap" v-loading="loading">
        <el-button type="primary" @click="updateHost">更新host(访问github)</el-button>
        <el-button type="success" @click='saveHost'>保存host</el-button>
        <el-button type="info" @click='openHostFolder'>打开hosts</el-button>
        <el-button type="warning" @click="updateDns">刷新dns</el-button>
    </el-row>

    <div class='text-panel-wrap'>
        <div class='text-panel'>
            <div class='text-panel-row' :class="[{ 'update': item.status === 'update' }, { 'add': item.status === 'add' }]"
                v-for='item in localHostText' :key="item"><span class='ip'>{{ item.ip }}</span><span>{{ item.hostname
                }}</span></div>
        </div>
    </div>
</template>
<style scoped lang="less">
.btn-wrap {
    padding: 20px;
    display: flex;
    width: 100%;
    height: 72px;
    position: fixed;
    top: 0;
    left: 0;
    background-color: #fff;
}

.text-panel {

  width: 100%;
  padding: 80px 20px;
  font-size: 14px;
  .text-panel-row {
    display: flex;
    &.update {
      span {
        background: #FFFE95;
      }

    }
    &.add {
      span {
        background: #5FFF9A;
      }
    }
    .ip {
      min-width: 140px;
    }
  }
}
</style>
